package com.example.amap.ui.map.ui.viewmodel.search

import androidx.compose.runtime.State
import androidx.compose.runtime.mutableStateOf
import androidx.lifecycle.viewModelScope
import com.example.amap.lib.base.utils.LogUtil
import com.example.amap.search.bean.SearchSuggestInfo
import com.example.amap.search.observer.ISearchObserver
import com.example.amap.ui.map.ui.viewmodel.BusinessViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

class SearchViewModel : BusinessViewModel() {
    companion object {
        private const val TAG = "SearchViewModel"
        private const val SEARCH_DEBOUNCE_TIME = 500L
    }

    private var searchJob: Job? = null

    private val _hasFocus = mutableStateOf(false)
    val hasFocus: State<Boolean> = _hasFocus

    private val _searchText = mutableStateOf("")
    val searchText: State<String> = _searchText

    private val _suggestList = mutableStateOf(emptyList<SearchSuggestInfo>())
    val suggestList: State<List<SearchSuggestInfo>> = _suggestList

    private val searchObserver = object : ISearchObserver {
        override fun onSearchSuggest(suggestList: List<SearchSuggestInfo>?) {
            LogUtil.d(TAG, "onSearchSuggest: $suggestList")
            _suggestList.value = suggestList ?: emptyList()
        }
    }

    init {
        getSearchService()?.addSearchObserver(searchObserver)
    }

    fun onFocusChange(hasFocus: Boolean) {
        _hasFocus.value = hasFocus
    }

    fun onSearchTextChange(text: String) {
        searchJob?.cancel()
        _searchText.value = text
        if (text.isEmpty()) {
            _suggestList.value = emptyList()
        } else {
            searchJob = viewModelScope.launch(Dispatchers.IO) {
                delay(SEARCH_DEBOUNCE_TIME)
                getSearchService()?.executeSearchSuggestion(text, getLocationService()?.getLocationInfo()?.city ?: "")
            }
        }
    }

    override fun onCleared() {
        getSearchService()?.removeSearchObserver(searchObserver)
    }
}